<?php 

	//echo '<pre >';
	//var_dump($_FILES);

	require "Mysql.php";
	
	class imgUpload extends Mysql{
		
		private $fileinfo;
		private $path = './upload/';
		private $filetype;
		
		//private $info;
		//private $newName;
		
		public function __construct() {
			
			parent::__construct();
			$this->fileinfo = $_FILES['pic'];
			$this->filetype = array('image/jpeg', 'image/jpg', 'image/ico', 'image/gif', 'image/png');
			
		}
		
		//上传图片
		public function upload(){
			//echo '<pre>';
			//print_r($this->fileinfo);
			//echo $this->fileinfo['name'];
			//检查是否有error
			if(!$this->check()){
				exit();
			}
			
			$newName = $this->newName();
			
			//将文件从tmp_upload文件夹中移动打uplaod文件夹中
			move_uploaded_file($this->fileinfo['tmp_name'], $this->path . $newName);
			$this->add($newName, $this->path . $newName, date('YmdHis'));
			//$this->add("test", "test", 123123123);
			
			echo '上传成功.';
		}
		
		private function check(){
			
			//判断是否有上传error
			if($this->fileinfo['error'] > 0){
				switch($this->fileinfo['error']){
					case 1:
						echo '文件大小超过限定的值.';
						return 0;
					case 2:
						echo '文件大小超过限定的值.';
						return 0;
					case 3:
						echo '文件只有部分上传.';
						return 0;
					case 4:
						echo '没有文件上传.';
						return 0;
					case 5:
						echo '文件上传为失败.';
						return 0;
					default:
						echo '文件上传失败.';
						return 0;
				}
			}
			
			//判断图片类型是否符合要求
			if(!in_array($this->fileinfo['type'], $this->filetype)){
				echo '图片类型不符.';
				return 0;
			}
			
			//检查图片是否为HTTP POST过来的文件，否则为非法上传
			if(is_uploaded_file($this->fileinfo['name'])){
				echo '非法上传.';
				return 0;
			}
			
			return 1;
		
		}
		
		//为上传图片获取新的文件名
		private function newName(){
			$info = pathinfo($this->fileinfo['name']);
			//echo '<pre>';
			//print_r($info);
			//do while循环，直到文件中没有与之重名的
			do{
				$newName = date('YmdHis') . rand(1000,4000) . '.' . $info['extension'];
			}
			while(file_exists($this->path . $newName));
			return $newName;
		}
		
	}
	
	$img = new imgUpload();
	
	$img->upload();
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
